import xgboost as xgb
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.datasets import load_breast_cancer
from sklearn.metrics import accuracy_score

# 加载数据集（这里以乳腺癌数据集为例）  
data = load_breast_cancer()
X, y = data.data, data.target

# 划分训练集和测试集  
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 初始化XGBClassifier  
xgb_clf = xgb.XGBClassifier(use_label_encoder=False, eval_metric='mlogloss')

# 定义网格搜索的参数网格  
param_grid = {
    'n_estimators': [100, 200, 300],
    'max_depth': [3, 5, 7],
    'learning_rate': [0.01, 0.1, 0.2],
    'subsample': [0.8, 0.9, 1.0],
    'colsample_bytree': [0.6, 0.8, 1.0]
}

# 初始化GridSearchCV  
grid_search = GridSearchCV(estimator=xgb_clf, param_grid=param_grid, cv=5, scoring='accuracy', verbose=1, n_jobs=-1)

# 执行网格搜索  
grid_search.fit(X_train, y_train)

# 输出最佳参数  
print("Best parameters found: ", grid_search.best_params_)

# 使用最佳模型进行预测  
best_model = grid_search.best_estimator_
y_pred = best_model.predict(X_test)

# 评估模型  
accuracy = accuracy_score(y_test, y_pred)
print("Test set accuracy: {:.2f}".format(accuracy))